import 'dart:convert';

import 'package:client_ui/api/api/ConnectApi.dart';

import 'package:client_ui/model/SendMsgModel.dart';
import 'package:flutter/cupertino.dart';
import 'package:provider/provider.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

import '../model/rest/RestCode.dart';
import '../model/rest/RestResult.dart';
import '../util/GenerateUtil.dart';
import '../util/GlobalData.dart';

class Request {
  static WebSocketChannel? _channel;
  static Request? request;

  Request._internal(WebSocketChannel webSocketChannel) {
    _channel = webSocketChannel;
  }

  static Request? getInstance() {
    if (request == null) {
      WebSocketChannel webSocketChannel =
          WebSocketChannel.connect(Uri.parse('ws://localhost:8080/ws'));
      request = Request._internal(webSocketChannel);
    }

    return request;
  }

  Stream<dynamic>? get stream => _channel?.stream;

  WebSocketChannel? get channel => _channel;

  void listenToMessages(BuildContext context) {
    stream?.listen((message) {
      // 处理接收到的消息
      print('Received message: $message');

      final globalData = Provider.of<GlobalData>(context, listen: false);
      RestResult result = RestResult.fromJson(jsonDecode(message));

      forwardService(result, globalData);
    }, onError: (error) {
      // 处理可能发生的错误
      print('Error: $error');
    }, onDone: () {
      // 处理连接关闭的情况
      print('Connection closed');
    });
  }

  void closeConnection() {
    _channel?.sink.close();
  }

  void forwardService(RestResult result, globalData) {
    if (result.code == RestCode.successSendMsg.code) {
      ConnectApi.addChatMsg(result, globalData);
    }
  }
}
